package com.temi.iot.jwt;

import com.temi.iot.exception.BizExceptionEnum;
import com.temi.iot.exception.ThrowsKit;
import com.temi.iot.jwt.model.TokenValue;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by
 *
 * @author sheng
 * @date 18/3/19.
 */
@Slf4j
@Service
public class DefaultTokenService implements TokenInterface {

    private static final Logger LOGGER = LoggerFactory.getLogger(TokenInterface.class);

    private static final String TOKEN_REDIS = "token_cake_";

    @Autowired
    private StringRedisTemplate template;


    @Autowired
    private JwtUtil jwt;


    /**
     * 获取token
     */
    @Override
    public String getToken(TokenValue tokenValue) throws Exception {
        String subject = JwtUtil.generalSubject(tokenValue);
        String token = jwt.createJWT(subject);
        try {
            ValueOperations<String, String> ops = template.opsForValue();
            ops.set(TOKEN_REDIS + token, String.valueOf(tokenValue.getRid()), 7, TimeUnit.DAYS);
        } catch (Exception e) {
            ThrowsKit.error(BizExceptionEnum.REDIS_NOT_CONNECTION);
        }
        return token;
    }

    /**
     * 获取30天Token
     * @param tokenValue
     * @return
     * @throws Exception
     */
    public String getTokenLong(TokenValue tokenValue) throws Exception {
        String subject = JwtUtil.generalSubject(tokenValue);
        String token = jwt.createJWT(subject);
        try {
            ValueOperations<String, String> ops = template.opsForValue();
            ops.set(TOKEN_REDIS + token, String.valueOf(tokenValue.getRid()), 1, TimeUnit.DAYS);
        } catch (Exception e) {
            ThrowsKit.error(BizExceptionEnum.REDIS_NOT_CONNECTION);
        }
        return token;
    }

    /**
     * 验证token
     */
    @Override
    public TokenValue verifyToken(String authorization) throws Exception {
        ThrowsKit.isEmpty(authorization, BizExceptionEnum.NO_PERMITION);
        Claims user;
        TokenValue.TokenValueBuilder tokenValue = TokenValue.builder();
        try {
            user = jwt.parseJWT(authorization);
            ThrowsKit.isEmpty(user, BizExceptionEnum.NO_PERMITION);
            ValueOperations<String, String> ops = template.opsForValue();
            ThrowsKit.isEmpty(ops.get(TOKEN_REDIS + authorization), BizExceptionEnum.NO_PERMITION);
            ops.set(TOKEN_REDIS + authorization, String.valueOf(user.get("rid")), 7, TimeUnit.DAYS);
            tokenValue.rid(Integer.parseInt(String.valueOf(user.get("rid"))));
            tokenValue.per((List<String>)user.get("per"));
            //tokenValue.pro(Integer.parseInt(String.valueOf(user.get("pro"))));
            tokenValue.oid(String.valueOf(user.get("oid")));
        } catch (Throwable throwable) {
            ThrowsKit.error(BizExceptionEnum.NO_PERMITION);
            throwable.printStackTrace();
        }
        return tokenValue.build();
    }

    /**
     * 删除token
     */
    @Override
    public void remove(String authorization) {
        try {
            template.delete(authorization);
        } catch (Exception e) {
            LOGGER.error("删除token失败", e);
        }
    }
}
